/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.spring.event;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;

import java.util.Collections;
import java.util.EventObject;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import lombok.Getter;

/**
 * @author william
 * @since 2024/3/29
 */
@Getter
public abstract class AbstractPropertyChangedEventHandler extends AbstractEventHandler implements InitializingBean {
    private final String propertyKey;
    private final boolean skipInitializing;

    protected AbstractPropertyChangedEventHandler(String propertyKey, boolean skipInitializing) {
        super(EnvironmentChangeEvent.class);
        this.propertyKey = Objects.requireNonNull(propertyKey);
        this.skipInitializing = skipInitializing;
    }

    @Override
    public boolean skipHandle(EventObject eventObject) {
        return super.skipHandle(eventObject) ||
                !this.getCandidateProperties((EnvironmentChangeEvent) eventObject).contains(this.propertyKey);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (!this.skipInitializing) {
            this.handle(null);
        }
    }

    private Set<String> getCandidateProperties(EnvironmentChangeEvent environmentChangeEvent) {
        if (environmentChangeEvent == null || CollectionUtils.isEmpty(environmentChangeEvent.getKeys())) {
            return Collections.emptySet();
        }
        return environmentChangeEvent
                .getKeys()
                .stream()
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());
    }
}
